package com.xianyun.site.auth.common.handler;

import com.xianyun.common.core.domain.Response;
import com.xianyun.common.core.utils.ServletUtils;
import com.xianyun.site.auth.common.config.system.LoginPageConfig;
import com.xianyun.site.auth.common.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败的回调
 *
 * @author songyinyin
 * @date 2020/2/25 下午 09:20
 */
@Slf4j
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private LoginPageConfig loginPageConfig;
    /**
     * 调整错误信息返回情况 只对非三方登录接口返回错误信息（包含绑定情况） 三方登录接口只做界面跳转
     * @param request 请求
     * @param response 响应
     * @param exception 权限异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException {
        response.setContentType("application/json;charset=utf-8");
        Response<Object> error = Response.fail("登录失败！");
        if (exception instanceof JustAuthLoginException){
            //加入错误信息在重定向Url后 具体要和前端同学商量
            response.sendRedirect(loginPageConfig.getLoginPage());
            return;
        }else if(exception instanceof BindErrorException){
            error.setMsg(exception.getMessage());
        }else if (exception instanceof LoginCheckException){
            error.setMsg(exception.getMessage());
        }else if (exception instanceof ExtendKeyException) {
            error.setMsg(exception.getMessage());
        } else if (exception instanceof LockedException) {
            error.setMsg("账户被锁定，请联系管理员！");
        } else if (exception instanceof CredentialsExpiredException) {
            error.setMsg("密码过期，请联系管理员！");
        } else if (exception instanceof AccountExpiredException) {
            error.setMsg("账户过期，请联系管理员！");
        } else if (exception instanceof DisabledException) {
            error.setMsg("账户被禁用，请联系管理员！");
        } else if (exception instanceof BadCredentialsException) {
            error.setMsg("用户名或密码输入错误，请重新输入！");
        }
        //转成字符串以便输出
        ServletUtils.getResultToCallBack(response,error);
    }
}
